package com.webrtc.demo

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.ArrayAdapter
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.webrtc.demo.call.*
import com.webrtc.demo.util.ContactsUtils
import com.webrtc.demo.util.logD
import kotlinx.android.synthetic.main.activity_chat.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import org.webrtc.PeerConnection
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.EasyPermissions


class ChatActivity : AppCompatActivity(), CoroutineScope by MainScope() {

    companion object {
        const val TAG = "ChatActivity"
        private const val RC_CAMERA_AND_AUDIO = 1001
        private const val RC_ADD_CONTACTS = 1002

        fun launch(context: Context, fromId: String, toId: String) {
            context.startActivity(
                Intent(context, ChatActivity::class.java)
                    .putExtra("fromId", fromId)
                    .putExtra("toId", toId)
            )
        }
    }

    private val fromId by lazy { intent.getStringExtra("fromId") }
    private val toId by lazy { intent.getStringExtra("toId") }

    private val connection by lazy { ConnectionManager.get(toId) }


    private val mAdapter by lazy {
        ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1)
    }


    private val listener: (String) -> Unit = {
        launch {
            mAdapter.add("你收到了：$it")
        }
    }

    private val connectionStateListener = object : ConnectionStateListener {
        override fun onConnectState(state: PeerConnection.PeerConnectionState) {
            launch {
                supportActionBar?.title = "连接状态: $state"
            }
        }
    }

    private val onVideoCallListener = { uid: String, cId: String? ->
        runOnUiThread {
            AlertDialog.Builder(this@ChatActivity)
                .setTitle("接受此联系人的视频邀请？")
                .setMessage(uid)
                .setPositiveButton("接受") { dialog, _ ->
                    callToUid = uid
                    this.cId = cId
                    isCaller = false
                    requiresPermissionsAfterCall()
                    dialog.dismiss()
                }
                .setNegativeButton("拒绝") { dialog, _ ->
                    dialog.dismiss()
                    if (cId == null) // 单人视频拒绝
                        RTCSignalClient.sendNegotiate(uid, Negotiate.DENY, MediaType.VIDEO) {
                            logD("RTCSignalClient", "已拒绝 $uid 的单人视频通话")
                        }
                    else { // 多人视频拒绝
                        RTCSignalClient.sendRoomNegotiate(uid,cId,RoomNegotiate.ROOM_DENY){
                            logD("RTCSignalClient", "已拒绝 $uid 的多人视频通话")
                        }
                    }
                }
                .setCancelable(false)
                .show()
        }
        true
    }

    private lateinit var callToUid: String
    private var isCaller = true
    private var cId: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_chat)

        supportActionBar?.title = "连接状态: ${connection.connectionState}"
        listView.adapter = mAdapter

        if (connection.connectionState != PeerConnection.PeerConnectionState.CONNECTED) {
            connection.connect()
        }
        // 连接
        btn_connect.setOnClickListener {
            connection.connect()
        }
        // 视频
        btn_video.setOnClickListener {

            if (!EasyPermissions.hasPermissions(
                    this,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO
                )
            ) {
                EasyPermissions.requestPermissions(
                    this,
                    "Need permissions for camera & microphone",
                    0,
                    Manifest.permission.CAMERA,
                    Manifest.permission.RECORD_AUDIO
                )
            } else {
                CallActivity.launch(this, fromId, toId, true)
            }

        }
        // 发送消息
        btn_send.setOnClickListener {

            val msg = et_msg.text.toString()
            if (msg.isNullOrEmpty()) {
                return@setOnClickListener
            }
            val send =
                connection.textStation.send(msg) && connection.connectionState == PeerConnection.PeerConnectionState.CONNECTED

            if (send) {
                mAdapter.add("你发送了：$msg")
                et_msg.text = null
            } else {
                mAdapter.add("发送消息失败")
            }

        }

        connection.textStation.registerListener(listener)
        connection.registerConnectionStatusListener(connectionStateListener)

        ConnectionManager.addOnVideoCallListener(onVideoCallListener)
    }

    @AfterPermissionGranted(RC_CAMERA_AND_AUDIO)
    private fun requiresPermissionsAfterCall() {
        val perms = arrayOf(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO
        )
        if (EasyPermissions.hasPermissions(this, *perms)) {
            val _cId = cId
            if (_cId == null) CallActivity.launch(
                this,
                ContactsUtils.getMyUid(this),
                callToUid,
                isCaller
            )
            else
                MultiCallActivity.launch(this, ArrayList(), _cId, callToUid)
        } else {
            EasyPermissions.requestPermissions(
                this,
                "Need permissions for camera & microphone",
                RC_CAMERA_AND_AUDIO,
                *perms
            )
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        cancel()
        connection.unregisterConnectionStatusListener(connectionStateListener)
        connection.textStation.unregisterListener(listener)
        ConnectionManager.removeVideoCallListener(onVideoCallListener)
//        connection.close()
//        RTCSignalClient.disconnect()
    }

}
